package com.wxy.config;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @author 47868
 */
@Configuration
public class RabbitMqSender {
    private static final Logger logger = LoggerFactory.getLogger(RabbitMqSender.class);
    private final RabbitTemplate rabbitTemplate;
    private final RabbitMqSendMessage rabbitMqSendMessage;
    @Autowired
    public RabbitMqSender(RabbitTemplate rabbitTemplate,
                          RabbitMqSendMessage rabbitMqSendMessage) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitMqSendMessage = rabbitMqSendMessage;
    }
    @PostConstruct
    public void init() {
        rabbitTemplate.setReturnsCallback(returnedMessage -> {  //消息发送到队列失败 通常是routingKey有问题
            logger.error("监听到了消息return callback");
            logger.debug("exchange: {}", returnedMessage.getExchange());
            logger.debug("routingKey: {}", returnedMessage.getRoutingKey());
            logger.debug("message: {}", returnedMessage.getMessage().getBody());
            logger.debug("replyCode: {}", returnedMessage.getReplyCode());
            logger.debug("replyText: {}", returnedMessage.getReplyText());
            rabbitMqSendMessage.sendMessage("dead.exchange", "deadKey", Arrays.toString(returnedMessage.getMessage().getBody()));
        });
        rabbitTemplate.setConfirmCallback((correlationData, ack, s) -> {    //消息发送到路由失败
            if (ack) {
                logger.debug("消息成功发送到交换器，ID: {}", correlationData.getId());
            } else {
                logger.error("消息发送到交换器失败，ID: {}, 原因: {}", correlationData.getId(), s);
            }
        });
    }
}
